package com.cyc.shiro;



import com.cyc.entity.Role;
import com.cyc.entity.User;
import com.cyc.service.OrderService;
import com.cyc.service.RoleService;
import com.cyc.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;


//认证+授权
@Component
public class UserRealm extends AuthorizingRealm {

@Autowired
protected UserService userService;

@Autowired
protected RoleService roleService;


//授权
@Override
protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
//创建授权对象
SimpleAuthorizationInfo info=new SimpleAuthorizationInfo();


//获取认证对象
User user=(User) SecurityUtils.getSubject().getPrincipal();
    List<Role> list = roleService.selectByUserId(user.getId());

    for (Role tbRole:list){
    info.addRole(tbRole.getRoleCode());
    }
    return info;

}

//认证操作
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
//得到用户名
String username=(String)token.getPrincipal();
//得到密码
String password=new String((char[])token.getCredentials());
User user=null;
try{
    user = userService.selectByUsername(username);
}catch (Exception e){
    e.printStackTrace();
}

if (user==null){
throw new UnknownAccountException();
}

////密码为密文
//String newPassword= String.valueOf(new Md5Hash(password,user.getSalt(),1024));
//if (!user.getPassword().equals(newPassword)){
//throw new IncorrectCredentialsException();
//}

 //密码为明文
 if (!user.getPassword().equals(password)){
 throw new IncorrectCredentialsException();
 }

//以上都正确 创建认证对象返回
//四个参数
// 1 认证对象 2 密码 3 盐值 4当前认证名字

SimpleAuthenticationInfo info=new SimpleAuthenticationInfo(user,user.getPassword(),null,getName());


return info;
}
}